import request from "@/axios/request";
import DataCharts from "@/components/DataCharts";


export default {
    name: "AdminHome",
    components: {
        DataCharts
    },
    data() {
        return {
            // 所有原始数据
            allData: [],
            // 当前页数据
            tableData: [],
            // 当前页码
            currentPage: 1,
            // 每页条数
            pageSize: 5,
            currentTab: 'tenant',
            loading: false,

            showCharts: false,
            chartsOptions: []
        };
    },
    computed: {
        paginatedData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.allData.slice(start, end);
        }
    },
    created() {
        this.fetchTableData('tenant');
    },
    methods: {
        async fetchTableData(type) {
            let url = "";
            switch (type) {
                case "tenant":
                    url = "/tenant/findAll";
                    break;
                case "landlord":
                    url = "/landlord/findAll";
                    break;
                case "house":
                    url = "/house/findAll";
                    break;
                default:
                    return;
            }

            this.loading = true;
            this.allData = [];
            this.tableData = [];
            this.currentTab = type;
            this.currentPage = 1;
            try {
                const res = await request.get(url);
                if (res.code === 200) {
                    this.allData = res.data || [];
                    this.tableData = this.paginatedData;
                    this.currentTab = type;
                    this.currentPage = 1;
                } else {
                    ElMessage.error(res.msg || "获取数据失败");
                }
            } catch (err) {
                ElMessage.error("网络错误，请稍后再试");
                console.error(err);
            } finally {
                this.loading = false;
            }
        },
        handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.tableData = this.paginatedData;
        },
        handlePageChange(page) {
            this.currentPage = page;
            this.tableData = this.paginatedData;
        },
        // 创建图表
        async createDataCharts() {
            this.currentTab = "charts";
            this.showCharts = false;

            try {
                const [tenantRes, landlordRes, houseRes, applicationRes, commentRes, favoriteRes] = await Promise.all([
                    request.get("/tenant/findAll"),      // 租客
                    request.get("/landlord/findAll"),    // 房东
                    request.get("/house/findAll"),       // 房源
                    request.get("/rental/findAll"), // 出租申请
                    request.get("/comment/findAll"),     // 评论
                    request.get("/favorite/findAll")     // 收藏
                ]);

                const houses = houseRes.data || [];
                const tenants = tenantRes.data || [];
                const landlords = landlordRes.data || [];
                const applications = applicationRes.data || [];
                const comments = commentRes.data || [];
                const favorites = favoriteRes.data || [];

                // 统计各地区房源数量
                const areaStats = {};
                houses.forEach(house => {
                    const area = house.area;
                    if (area) {
                        areaStats[area] = (areaStats[area] || 0) + 1;
                    }
                });

                this.applicationCount = applications.length;
                this.commentCount = comments.length;
                this.favoriteCount = favorites.length;

                const userChart = this.createUserPieChart(tenants.length, landlords.length);
                const priceChart = this.createPriceBarChart(houses);
                const areaChart = this.createAreaPieChart(houses);
                const statusChart = this.createStatusBarChart(houses);
                const statsChart = this.createStatsBarChart();
                const mapChart = this.createMapChart(areaStats);

                this.chartsOptions = [userChart, priceChart, areaChart, statusChart, statsChart, mapChart];

                this.showCharts = true;

            } catch (err) {
                console.error("图表加载失败", err);
                this.$message.error("图表加载失败");

                this.chartsOptions = [
                    this.createUserPieChart(0, 0),
                    this.createPriceBarChart([]),
                    this.createAreaPieChart([]),
                    this.createStatusBarChart([]),
                    this.createStatsBarChart(),
                    this.createMapChart({})
                ];
                
                this.showCharts = true;
            }
        },
        // 用户总数嵌套饼图
        createUserPieChart(tenantCount, landlordCount) {
            return {
                type: 'pie',
                width: '600px',
                height: '400px',
                option: {
                    title: {
                        text: '用户总人数分布',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c}人 ({d}%)'
                    },
                    series: [
                        {
                            name: '用户类型',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            avoidLabelOverlap: false,
                            label: { show: false },
                            emphasis: {
                                label: {
                                show: true,
                                fontSize: '20',
                                fontWeight: 'bold'
                                }
                            },
                            data: [
                                { value: tenantCount, name: '租客', itemStyle: { color: '#FFA726' } },
                                { value: landlordCount, name: '房东', itemStyle: { color: '#42A5F5' } }
                            ]
                        },
                        {
                            name: '总人数',
                            type: 'pie',
                            radius: ['0%', '30%'],
                            label: { show: false },
                            data: [{ value: tenantCount + landlordCount, name: '总人数', itemStyle: { color: '#66BB6A' } }],
                            emphasis: {
                                label: {
                                    show: true,
                                    position: 'center',
                                    textStyle: {
                                        fontSize: '20',
                                        fontWeight: 'normal'
                                    }
                                }
                            }
                        }
                    ]
                }
            };
        },
        // 房源价格柱状图
        createPriceBarChart(houses) {
            const low = houses.filter(h => h.price >= 1000 && h.price <= 5000).length;
            const mid = houses.filter(h => h.price > 5000 && h.price <= 10000).length;
            const high = houses.filter(h => h.price > 10000 && h.price <= 100000).length;
            console.log(low, mid, high);

            return {
                type: 'bar',
                width: '600px',
                height: '400px',
                option: {
                    title: { text: '房源价格区间分布', left: 'center' },
                    tooltip: {},
                    xAxis: {
                        type: 'category',
                        data: ['低价房源', '中价房源', '高价房源']
                    },
                    yAxis: { type: 'value' },
                    series: [{
                        name: '数量',
                        type: 'bar',
                        data: [low, mid, high],
                        itemStyle: { color: "#AB47BC" }
                    }]
                }
            };
        },
        // 房屋面积饼图
        createAreaPieChart(houses) {
            const small = houses.filter(h => h.size <= 50).length;
            const medium = houses.filter(h => h.size > 50 && h.size <= 100).length;
            const large = houses.filter(h => h.size > 100).length;

            return {
                type: 'pie',
                width: '600px',
                height: '400px',
                option: {
                    title: { text: '房屋面积分布', left: 'center' },
                    tooltip: { trigger: 'item' },
                    legend: { top: '10%', left: 'right' },
                    series: [{
                        name: '面积分布',
                        type: 'pie',
                        radius: '60%',
                        data: [
                            { value: small, name: '小面积', itemStyle: { color: '#26A69A' } },
                            { value: medium, name: '中面积', itemStyle: { color: '#29B6F6' } },
                            { value: large, name: '大面积', itemStyle: { color: '#FF7043' } }
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }]
                }
            };
        },
        // 房源状态柱状图
        createStatusBarChart(houses) {
            const available = houses.filter(h => h.status === 'available').length;
            const rented = houses.filter(h => h.status === 'rented').length;
            const pending = houses.filter(h => h.status === 'pending').length;
            const rejected = houses.filter(h => h.status === 'rejected').length;

            return {
                type: 'bar',
                width: '600px',
                height: '400px',
                option: {
                    title: { text: '房源状态统计', left: 'center' },
                    tooltip: {},
                    xAxis: {
                        type: 'category',
                        data: ['可租', '已租', '待审核', '已拒绝']
                    },
                    yAxis: { type: 'value' },
                    series: [{
                        name: '数量',
                        type: 'bar',
                        data: [available, rented, pending, rejected],
                        itemStyle: { color: '#EC407A' }
                    }]
                }
            };
        },
        // 出租申请、评论、收藏统计图
        createStatsBarChart() {
            return {
                type: 'bar',
                width: '600px',
                height: '400px',
                option: {
                    title: { text: '网站热度指标统计', left: 'center' },
                    tooltip: {},
                    xAxis: {
                        type: 'category',
                        data: ['出租申请', '评论', '收藏']
                    },
                    yAxis: { type: 'value' },
                    series: [{
                        name: '数量',
                        type: 'bar',
                        data: [this.applicationCount, this.commentCount, this.favoriteCount],
                        itemStyle: { color: '#26A69A' }
                    }]
                }
            };
        },
        // 地图热力图
        createMapChart(areaStats) {
            console.log(areaStats);
            // const data = Object.entries(areaStats || {}).map(([name, value]) => ({ name, value }));
            const data = Object.entries(areaStats).map(([name, value]) => ({ name, value }));

            // const rawData = Object.entries( {
            //     北京市: 100,
            //     天津市: 80,
            //     河北省: 60,
            //     山西省: 40,
            //     内蒙古自治区: 20,
            //     辽宁省: 10,
            //     吉林省: 5,
            //     黑龙江省: 0,
            //     上海市: 90,
            //     江苏省: 80,
            //     浙江省: 70,
            //     安徽省: 60,
            //     福建省: 50,
            //     江西省: 40,
            //     山东省: 30,
            //     河南省: 20,
            //     湖北省: 10,
            //     湖南省: 5,
            //     广东省: 80,
            //     广西壮族自治区: 70,
            //     海南省: 60,
            //     重庆市: 90,
            //     四川省: 50,
            //     贵州省: 40,
            //     云南省: 30,
            //     西藏自治区: 20,
            //     陕西省: 10,
            //     甘肃省: 5,
            //     青海省: 0,
            //     宁夏回族自治区: 90,
            //     新疆维吾尔自治区: 80,
            //     台湾省: 80,
            //     香港特别行政区: 70,
            //     澳门特别行政区: 60
            // } );

            // const data = [
            //     { name: '北京市', value: 100, },
            //     { name: '天津市', value: 80, },
            //     { name: '河北省', value: 60, },
            //     { name: '山西省', value: 40, },
            //     { name: '内蒙古自治区', value: 20, },
            //     { name: '辽宁省', value: 10, },
            //     { name: '吉林省', value: 5, },
            //     { name: '黑龙江省', value: 0, },
            //     { name: '上海市', value: 90, },
            //     { name: '江苏省', value: 80, },
            //     { name: '浙江省', value: 70, },
            //     { name: '安徽省', value: 60, },
            //     { name: '福建省', value: 50, },
            //     { name: '江西省', value: 40, },
            //     { name: '山东省', value: 30, },
            //     { name: '河南省', value: 20, },
            //     { name: '湖北省', value: 10, },
            //     { name: '湖南省', value: 5, },
            //     { name: '广东省', value: 0, },
            //     { name: '广西壮族自治区', value: 90, },
            //     { name: '重庆市', value: 70, },
            //     { name: '四川省', value: 60, },
            //     { name: '贵州省', value: 50, },
            //     { name: '云南省', value: 40, },
            //     { name: '西藏自治区', value: 30, },
            //     { name: '陕西省', value: 20, },
            //     { name: '甘肃省', value: 10, },
            //     { name: '青海省', value: 5, },
            //     { name: '宁夏回族自治区', value: 0, },
            //     { name: '新疆维吾尔自治区', value: 90, },
            //     { name: '台湾省', value: 80, },
            //     { name: '香港特别行政区', value: 70, },
            //     { name: '澳门特别行政区', value: 60, },
            //     { name: '', value: 60, }
            // ]


            console.log(data);

            return {
                type: 'map',
                width: '100%',
                height: '700px',
                option: {
                    title: { text: '各地区房源数量热力图', left: 'center' },
                    tooltip: { trigger: 'item' },
                    visualMap: {
                        show: true,
                        min: Math.min(...data.map(d => d.value)) || 0,
                        max: Math.max(...data.map(d => d.value)) || 100,
                        inRange: {
                            color: ['lightskyblue', 'yellow', 'orangered']
                        },
                        text: ["High", "Low"],
                        calculable: true
                    },
                    geo: {
                        map: "china",
                        roam: true,
                        label: { emphasis: { show: false } },
                        itemStyle: {
                            normal: { areaColor: "#f7fbff", borderColor: "#9ec2cf" },
                            emphasis: { areaColor: "#2a333d" }
                        }
                    },
                    series: [{
                        name: '房源数量',
                        type: 'map',
                        coordinateSystem: 'geo',
                        geoIndex: 0,
                        data: data,
                    }]
                }
            };
        }
    },
};